package com.hxy.network.core.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

/**
 * @description: netty 启动服务端
 * @program: component_code_integration
 * @author: HCY
 * @create: 2022/12/07 14:22
 */
@Component
@Slf4j
public class NettyService {

    @Resource
    private ServerHandler serverHandler;
    private EventLoopGroup bossGroup = new NioEventLoopGroup();
    private EventLoopGroup workGroup = new NioEventLoopGroup();


    @Value("${netty.serverPort}")
    private int serverPort ;
    @Value("${netty.serverPort02}")
    private int serverPort02 ;
    @PostConstruct
    public void startService() throws InterruptedException {
        ServerBootstrap b = new ServerBootstrap();
        try {
            b.group(bossGroup,workGroup)
                    .childHandler(new ChannelInitializer<SocketChannel>()  {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(serverHandler);
                            socketChannel.pipeline().addLast("decoder", new StringDecoder());
                            socketChannel.pipeline().addLast("encoder", new StringEncoder());
                            socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(65535
                                    , 0, 2, 0, 2));
                            socketChannel.pipeline().addLast(new LengthFieldPrepender(2));
                        }
                    })
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,128);
            ChannelFuture future = b.bind(serverPort).sync();
//            ChannelFuture future1 = b.bind(serverPort02).sync();
            if (future.isSuccess()) {
                log.info("netty服务端启动成功，端口：{}",serverPort);
            }
//            if (future1.isSuccess()) {
//                log.info("netty服务端启动成功，端口：{}",serverPort02);
//            }
            // 优雅监听关闭连接
            future.channel().closeFuture();
//            future1.channel().closeFuture();
        } catch (Exception e) {
            log.error("netty服务启动异常",e.getMessage(), e);
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }

    }

    /**
     * 销毁
     */
    @PreDestroy
    public void destroy() {
        bossGroup.shutdownGracefully().syncUninterruptibly();
        workGroup.shutdownGracefully().syncUninterruptibly();
        System.out.println("关闭 Netty服务 成功");
    }


}
